const BASE_URL = process.env.VUE_APP_API_BASE_SOCKET_URL
let socketInstance = null;

// 使用方式
// mounted() {
//     this.handleWebsocketMessage = (event) => {
//         //处理消息
//     };
//     window.addEventListener('websocket-message', this.handleWebsocketMessage);
// },
// beforeDestroy() {
//     window.removeEventListener('websocket-message', this.handleWebsocketMessage);
// }
export default {
    init(userId) {
        if (socketInstance && socketInstance.readyState === WebSocket.OPEN) {
            return socketInstance; // 已连接则复用
        }
        const url = `${BASE_URL}/${encodeURIComponent(userId)}`;
        socketInstance = new WebSocket(url);
        // 事件监听
        socketInstance.onopen = () => {
            console.log('WebSocket 连接成功');
        };
        socketInstance.onmessage = (event) => {
            console.log('收到消息:', event.data);
            window.dispatchEvent(new CustomEvent('websocket-message', {detail: event.data}));
        };
        return socketInstance;
    },
    close() {
        if (socketInstance) {
            socketInstance.close();
            socketInstance = null;
        }
    },
    isOpen() {
        return socketInstance && socketInstance.readyState === WebSocket.OPEN;
    }
};
